package com.example.demo.config;

import com.example.demo.intercepter.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class myWebConfig implements WebMvcConfigurer {
    // 重写addInterceptors方法，添加自定义拦截器

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("http://example.com", "http://another-example.com") // 显式列出允许的来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    //创建拦截器Bean
    @Bean
    public MyInterceptor createMyInterceptorBean() {
        return new MyInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns("/**")表示拦截所有请求
        //excludePathPatterns()表示排除请求
        registry.addInterceptor(createMyInterceptorBean()).addPathPatterns("/**")
                .excludePathPatterns("/swagger-ui.html")
                .excludePathPatterns("/index.html")
                .excludePathPatterns("/images/**")
                .excludePathPatterns("/user/register")
//                .excludePathPatterns("/user/select")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }

    // 重写addResourceHandlers方法，添加swagger-ui.html的资源路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}


